from flask import request, current_app
from flask_restx import Resource, Namespace, fields
from app.services.user_discovery_service import UserDiscoveryService
from app.utils.auth import user_token_required, get_current_user_optional
from app.utils.response import success_response, error_response
from . import api

# 命名空间
discover_ns = Namespace('discover', description='用户发现与搜索')

user_basic_model = discover_ns.model('UserBasic', {
    'id': fields.Integer,
    'nickname': fields.String,
    'gender': fields.Integer,
    'age': fields.Integer,
    'city': fields.String,
    'avatar': fields.String
})

@discover_ns.route('/discover')
class DiscoverAPI(Resource):
    def get(self):
        """
        发现用户列表 - 支持未登录访问
        未登录时返回热门用户，登录后根据用户偏好返回推荐用户
        """
        page = int(request.args.get('page', 1))
        limit = int(request.args.get('limit', 10))
        city = request.args.get('city')
        
        try:
            # 尝试获取当前用户（可能为None）
            current_user = get_current_user_optional()
            user_id = current_user.id if current_user else None
            
            # 调试日志
            current_app.logger.info(f"发现用户API - 用户ID: {user_id}, 页码: {page}, 每页数量: {limit}, 城市: {city}")
            
            # 获取用户列表
            users, total = UserDiscoveryService.discover_users(user_id, page, limit, city)
            
            return success_response({'items': users, 'total': total}, '获取成功')
        except Exception as e:
            current_app.logger.error(f"发现用户失败: {str(e)}")
            import traceback
            current_app.logger.error(traceback.format_exc())
            return error_response(str(e), 500)

@discover_ns.route('/search')
class SearchAPI(Resource):
    @user_token_required
    def get(self, current_user):
        filters = {
            'gender': request.args.get('gender', type=int),
            'min_age': request.args.get('min_age', type=int),
            'max_age': request.args.get('max_age', type=int),
            'city': request.args.get('city')
        }
        page = int(request.args.get('page', 1))
        limit = int(request.args.get('limit', 10))
        try:
            users, total = UserDiscoveryService.search_users(filters, page, limit)
            return success_response({'items': users, 'total': total}, '获取成功')
        except Exception as e:
            current_app.logger.error(str(e))
            return error_response(str(e), 500)

# 注册命名空间
api.add_namespace(discover_ns) 